package com.tamtamy.jtta.data.xml;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.tamtamy.jtta.data.GroupList;
import com.tamtamy.jtta.exception.NoResultException;
import com.tamtamy.jtta.exception.ParsingException;

public class XMLGroupList extends GroupList {

	private static final long serialVersionUID = 3676826071425289961L;

	private static final String KCLGROUP = "it.reply.tt.rest.entity.KcLGroup";
	
	public XMLGroupList(Document xmlDocument) throws NoResultException, ParsingException {
		super();
		NodeList groupNodeList = xmlDocument.getElementsByTagName(KCLGROUP);
		if (groupNodeList == null || groupNodeList.getLength()==0){
			throw new NoResultException("No " + KCLGROUP + " element found");
		}
		for (int i = 0; i < groupNodeList.getLength(); i++) {
			Node groupNode = groupNodeList.item(i);
			try {
				Document groupDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
				groupDocument.appendChild(groupDocument.importNode(groupNode, true));
				this.add(new XMLGroup(groupDocument)); 
			} catch (ParserConfigurationException parserConfigurationException) {
				throw new ParsingException("Error parsing " + KCLGROUP + " element : " + parserConfigurationException.getMessage());
			}   
		}		
	
	}
}
